﻿using System.Threading.Tasks;

namespace 请求取消
{
    internal class Program
    {
        //超时取消
        //static async Task Main(string[] args)
        //{
        //    CancellationTokenSource cts = new CancellationTokenSource(2000);
        //    //cts.CancelAfter(2000);

        //    //await Download1Async("https://www.baidu.com", 100,cts.Token);
        //    await Download2Async("https://www.baidu.com", 100, cts.Token);
        //}

        //手动取消
        static async Task Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource(); 
            Download1Async("https://www.baidu.com", 100, cts.Token);
            while (Char.ToUpper(Console.ReadKey().KeyChar) != 'Q')
            {

            }

            //用户输入q后取消下载
            cts.Cancel();
        }

        static async Task Download1Async(string url, int count,CancellationToken cancellationToken)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                for (int i = 0; i < count; i++)
                {

                    //方式一：
                    if (cancellationToken.IsCancellationRequested)
                    {
                        Console.WriteLine("下载取消");
                        break; //return;
                    }

                    //方式二：                    
                    //cancellationToken.ThrowIfCancellationRequested(); //请求取消时抛出异常

                    string content = await httpClient.GetStringAsync(url);
                    Console.WriteLine($"第{ i+1 }次下载：\n");
                    Console.WriteLine(content);
                }
            }
            
        }

        static async Task Download2Async(string url, int count, CancellationToken cancellationToken)
        {
            using(HttpClient  httpClient = new HttpClient())
            {
                for (int i = 0; i < count; i++)
                {
                    //方式三
                    var resp = await httpClient.GetAsync(url, cancellationToken);//请求取消时抛出异常
                    string html=await resp.Content.ReadAsStringAsync();
                    Console.WriteLine($"第{i + 1}次下载：\n");
                    Console.WriteLine(html);
                }
            }
        }
    }
}
